angular
.module('qa', [
	'ui.router',
	'qa.directives','qa.navbar.directive','ui.bootstrap','ngSanitize'],function($httpProvider) {
	// Use x-www-form-urlencoded Content-Type
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
 
	/**
	* The workhorse; converts an object to x-www-form-urlencoded serialization.
	* @param {Object} obj
	* @return {String}
	*/ 
	var param = function(obj) {
	var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
	for(name in obj) {
	  value = obj[name];
	    
	  if(value instanceof Array) {
	    for(i=0; i<value.length; ++i) {
	      subValue = value[i];
	      fullSubName = name + '[' + i + ']';
	      innerObj = {};
	      innerObj[fullSubName] = subValue;
	      query += param(innerObj) + '&';
	    }
	  }
	  else if(value instanceof Object) {
	    for(subName in value) {
	      subValue = value[subName];
	      fullSubName = name + '[' + subName + ']';
	      innerObj = {};
	      innerObj[fullSubName] = subValue;
	      query += param(innerObj) + '&';
	    }
	  }
	  else if(value !== undefined && value !== null)
	    query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
	}
	return query.length ? query.substr(0, query.length - 1) : query;
	};
 
  	// Override $http service's default transformRequest
	$httpProvider.defaults.transformRequest = [function(data) {
		return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
	}];
})
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
	$urlRouterProvider.otherwise('/');
	$stateProvider
	.state('home', {
		url: '/',
		templateUrl: 'templates/home.html',
		controller: 'homeCtrl'
		})
	.state('add', {
		url: '/add',
		templateUrl: 'templates/add.html',
		controller: 'addCtrl'
	})
	.state('detail', {
		url: '/detail/:aqid',
		templateUrl: 'templates/detail.html',
		controller: 'detailCtrl'
	})
	.state('followed', {
		url: '/followed',
		templateUrl: 'templates/followed.html',
		controller: 'followedCtrl'
	})
}])
.factory('QuestionsService', ['$http', function($http) {
	return {
		get: function(data) {
			return $http({
				method: 'GET',
				withCredentials: true,
				url: "http://api.mengma.com/questions",
				params: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		},
		operation: function(method, data) {
			return $http({
				method: method,
				withCredentials: true,
				url: "http://api.mengma.com/questions",
				data: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}
	}
}])
.factory('AttentionsService', ['$http', function($http) {
	return {
		operation: function(method, data) {
			return $http({
				method: method,
				withCredentials: true,
				url: "http://api.mengma.com/attentions",
				data: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}
	}
}])
.factory('AnswersService', ['$http', function($http) {
	return {
		operation: function(method, data) {
			return $http({
				method: method,
				withCredentials: true,
				url: "http://api.mengma.com/answers",
				data: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		},
		get: function(data) {
			return $http({
				method: 'GET',
				withCredentials: true,
				url: "http://api.mengma.com/answers",
				params: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}

	}
}])
.factory('CommentService', ['$http', function($http) {
	return {
		get: function(data) {
			return $http({
				method: 'GET',
				withCredentials: true,
				url: "http://api.mengma.com/comments",
				params: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		},
		operation: function(method, data) {
			return $http({
				method: method,
				withCredentials: true,
				url: "http://api.mengma.com/comments",
				data: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}
	}
}])
.factory('UserService', ['$http', function($http) {
	return {
		get: function() {
			return $http({
				method: 'GET',
				withCredentials: true,
				url: "http://api.mengma.com/user",
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}

	}
}])
.factory('getInforService', ['$http', function($http) {
	return {
		get: function(url) {
			return $http({
				method: 'GET',
				withCredentials: true,
				url: url,
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		},
		operation: function(url, data, method) {
			return $http({
				method: method,
				withCredentials: true,
				url: url,
				data: data
			})
			.success(function(data, status, headers, config) {
				return data;
			})
		}

	}
}])
.controller('addCtrl',['$scope','QuestionsService',function($scope, QuestionsService) {
	toolbar = ['bold', 'italic', 'underline', '|', 'code', 'image', 'link', '|', 'ol', 'ul', 'blockquote', 'strikethrough','|', 'markdown'];
	editor = new Simditor({
		textarea: $("#editor-new"),
		placeholder: '请在这里输入问题描述（上传图片大小不能超过2M）',
		toolbar: toolbar,
		pasteImage: true,
		cleanPaste: true,
		upload: {
			url: 'http://api.mengma.com/questions/upload',
		},
	});
	$scope.title = "";
	$scope.titleNum = $scope.title.length;
	$scope.titleCount = function() {
		$scope.titleNum = $scope.title.length;
	}
	$scope.popup = function(determine,title,func) {
		if(determine) {
			config = {
				width: 300,
				height: 350,
				template: document.getElementById('integral_template').innerHTML,
				data: {
					color: "#36b14a",
					title: title,
					description: "积分+10"
				}
			}
		} else {
			config = {
				width: 500,
				height: 300,
				template: document.getElementById('tip_template').innerHTML,
				data: {
					color: "#b9b9bd",
					face: ":(",
					title: title
				}
			}
		}
		
		Phenix.init(config).show(function() {
			
			if(func != undefined) {
				setTimeout(function() {
					Phenix.hide();
					setTimeout(function() {
						func();
					},400);
				},2600);
			} else {
				setTimeout(function() {
					Phenix.hide();
				},3000);
			}
		});
	}
	$scope.submit = function() {
		if($scope.titleNum < 10) {
			$scope.popup(false, "标题需要10~35个字符！");
			return;
		}
		content = $("#editor-new").val();
		if((encodeURIComponent(content).length > 60000)) {
			$scope.popup(false, "输入的内容超过长度限制");
			return;
		}
		tagContent = []
		tagContent[0] = $scope.tag1;
		tagContent[1] = $scope.tag2;
		tagContent[2] = $scope.tag3;
		param = {
			title: $scope.title,
			content: content,
			tags: tagContent,
			type: 2
		}
		QuestionsService.operation('POST',param).success(function(data) {
			function goHome() {
				window.location.href = "http://qa.mengma.com/#/";
			}
			if(data.code == 200002) {
				$scope.popup(true, '提问成功', goHome);
			} else {
				$scope.popup(false, data.msg);
			}
		});
	}
}])
.controller('homeCtrl', ['$scope','QuestionsService','AttentionsService','AnswersService', function($scope,QuestionsService,AttentionsService,AnswersService) {
	$scope.questionConShow = false;
	$scope.getQuestionsPage = [0,0,0];
	$scope.tagtype;
	$scope.getQuestion = function(tagtype, determineLoadMore) {
		$scope.tagtype = tagtype;
		param = {
			page: $scope.getQuestionsPage[tagtype],
			tagtype: tagtype
		}
		QuestionsService.get(param).success(function(data) {
			if(!($scope.questions)) {
				$scope.questions = [];
			}
			for(var i = 0; i < data.questions.length; i++) {
				data.questions[i].user.name = data.questions[i].user.name == "" ? ("萌小码_"+ data.questions[i].uid) : data.questions[i].user.name
				if(determineLoadMore) {
					try {
						$scope.questions.push(data.questions[i]);
					}catch(e){
						console.log(e);
					}
				} else {
					try {
						$scope.questions = data.questions;
					} catch(e){
						conso.log(e);
					}
				}
			}
			$scope.quesLoadMore = data.loadmore;
		});
	}
	$scope.tabs = [
	    {title : '最新问题' ,content : ''},
	    {title : '热门问题' ,content : ''},
	    {title : '等待回答' ,content : ''},
	];
	
	$scope.questionLoadMore = function() {
		$scope.getQuestionsPage[$scope.tagtype]++;
		$scope.getQuestion($scope.tagtype, true);
	}
	$scope.getQuestion(0);
	
	$scope.attentionQuestion = function(index) {
		if(!$scope.isLogin) {
			$("#login_tip").css("display","block");
		} else {
			if(index == undefined) {
				question = $scope.question;
			} else {
				question = $scope.questions[index];
			}
			aqid = question.aqid;
			AttentionsService.operation('POST', {aqid:aqid}).success(function(data) {
				if(data.code == 0) {
					question.followed = "1";
					$scope.myAttentedQNum = parseInt($scope.myAttentedQNum) + 1;
				} else {
					$scope.popup(false, data.msg);
				}
			});
		}
	}
	$scope.cancelAttention = function(index) {
		if(!$scope.isLogin) {
			$("#login_tip").css("display","block");
		} else {
			if(index == undefined) {
				question = $scope.question;
			} else {
				question = $scope.questions[index];
			}
			aqid = question.aqid;
			AttentionsService.operation('DELETE', {aqid:aqid}).success(function(data) {
				if(data.code == 0) {
					question.followed = "0";
					$scope.myAttentedQNum = parseInt($scope.myAttentedQNum) - 1;
				} else {
					$scope.popup(false, data.msg);
				}
			});
		}
	}
	$scope.goQuestionDetail = function(index) {
		aqid = $scope.questions[index].aqid;
		$scope.isLoginVerify("detail/"+aqid);
	}
	$scope.goback = function() {
		$scope.searchShow = false;
	}
}])
.controller('detailCtrl',['$scope','QuestionsService','AnswersService','AttentionsService','$sce', function($scope, QuestionsService, AnswersService,AttentionsService,$sce) {
	$scope.answerPage = 0;
	$scope.attentionQuestion = function(index) {
		if(!$scope.isLogin) {
			$("#login_tip").css("display","block");
		} else {
			if(index == undefined) {
				question = $scope.question;
			} else {
				question = $scope.questions[index];
			}
			aqid = question.aqid;
			AttentionsService.operation('POST', {aqid:aqid}).success(function(data) {
				if(data.code == 0) {
					question.followed = "1";
					$scope.myAttentedQNum = parseInt($scope.myAttentedQNum) + 1;
				} else {
					$scope.popup(false, data.msg);
				}
			});
		}
	}
	$scope.cancelAttention = function(index) {
		if(index == undefined) {
			question = $scope.question;
		} else {
			question = $scope.questions[index];
		}
		aqid = question.aqid;
		AttentionsService.operation('DELETE', {aqid:aqid}).success(function(data) {
			if(data.code == 0) {
				question.followed = "0";
				$scope.myAttentedQNum = parseInt($scope.myAttentedQNum) - 1;
			} else {
				$scope.popup(false, data.msg);
			}
		});
	}
	$scope.getAnswers = function(param, determineLoadMore) {
		AnswersService.get(param).success(function(data) {
			if(data) {
				if(data.t != null) {
					data.t[0].user.name = data.t[0].user.name == "" ? ("萌小码_"+ data.t[0].uid) : data.t[0].user.name;
					data.t[0].content = data.t[0].content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace('/<a\s*href/g', '<a target="_blank" href>')
					data.t[0].content = $sce.trustAsHtml(data.t[0].content);
					$scope.answer_t = data.t[0];
					$scope.answer_t.commented = false;
				}
				if(data.s != null) {
					if(!($scope.answer_s)) {
						$scope.answer_s = [];
					}
					try {
						for(var i = 0; i < data.s.list.length; i++) {
							data.s.list[i].user.name = data.s.list[i].user.name == "" ? ("萌小码_"+ data.s.list[i].user.uid) : data.s.list[i].user.name
							data.s.list[i].content = data.s.list[i].content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace('/<a\s*href/g', '<a target="_blank" href>')
							data.s.list[i].content = $sce.trustAsHtml(data.s.list[i].content);
							data.s.list[i].commented = false;
							if(determineLoadMore) {
								$scope.answer_s.push(data.s.list[i]);
							}
						}
					}catch(e){
						console.log(e);
					}
					if(!determineLoadMore) {
						$scope.answer_s = data.s.list;
					}
					$scope.answerLoadMoreShow = data.s.loadmore;
				}
			}
		});
	}
	$scope.getQuestionDetial = function() {
		link = (window.location.href).split('/');
		$scope.aqid = link[(link.length - 1)];
		param = {
			aqid: $scope.aqid,
			fields: "qa"
		}
		QuestionsService.get(param).success(function(data) {
			if(data) {
				if(data.code == "400000") {
					window.location.href = "http://qa.mengma.com/#/"
				} else {
					$scope.indexShow = false;
					$scope.question = {};
					data.user.name = data.user.name == "" ? ("萌小码_"+ data.uid) : data.user.name;
					$scope.questionConShow = true;
					try {
						data.content = data.content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace(/<a\s*href/g, '<a target="_blank" href');
						result = $sce.trustAsHtml(data.content);
					} catch(e) {
						console.log(e);
					}
					$scope.question = data;
					$scope.question.content = result;
					$scope.quesLoadMore = false;
					$scope.question.answered = false;
					$scope.question.cogListShow = false;
					$scope.question.supply = false;
					$scope.question.supplyContent = "";
				}
			}
		});
		$scope.getAnswers(param, false);
	}
	$scope.getQuestionDetial();
}])
.directive('compile', ['$compile', function ($compile) {
	return function(scope, element, attrs) {
		scope.$watch(
		function(scope) {
		  return scope.$eval(attrs.compile);
		},
		function(value) {
		  element.html(value);
		  $compile(element.contents())(scope);
		}
	)};
}])
.controller('followedCtrl',['$scope','QuestionsService','AnswersService','$sce', function($scope, QuestionsService, AnswersService, $sce) {
	$scope.questionConShow = false;
	$scope.questionFollowed = true;
	$scope.getQuestionPage = 0;

	$scope.getAnswers = function(param, determineLoadMore) {
		AnswersService.get(param).success(function(data) {
			if(data) {
				if(data.t != null) {
					try {
						data.t[0].content = data.t[0].content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace('/<a\s*href/g', '<a target="_blank" href>')
						data.t[0].content = $sce.trustAsHtml(data.t[0].content);
						$scope.answer_t = data.t[0];
						$scope.answer_t.commented = false;
					}catch(e){}
					
				}
				if(data.s != null) {
					if(!($scope.answer_s)) {
						$scope.answer_s = [];
					}
					try {
						for(var i = 0; i < data.s.list.length; i++) {
							data.s.list[i].user.name = data.s.list[i].user.name == "" ? ("萌小码_"+ data.s.list[i].user.uid) : data.s.list[i].user.name
							data.s.list[i].content = data.s.list[i].content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace('/<a\s*href/g', '<a target="_blank" href>')
							data.s.list[i].content = $sce.trustAsHtml(data.s.list[i].content);
							data.s.list[i].commented = false;
							if(determineLoadMore) {
								$scope.answer_s.push(data.s.list[i]);
							}
						}
					}catch(e){}
					if(!determineLoadMore) {
						$scope.answer_s = data.s.list;
					}
					$scope.answerLoadMoreShow = data.s.loadmore;
				}
			}
		});
	}
	$scope.getQuestionDetial = function(aqid) {
		param = {
			aqid: aqid,
			fields: "qa"
		}
		QuestionsService.get(param).success(function(data) {
			if(data) {
				$scope.indexShow = false;
				$scope.question = {};
				data.user.name = data.user.name == "" ? ("萌小码_"+ data.uid) : data.user.name;
				try {
					data.content = data.content.replace(/<img\s*src/g, '<img ng-click="zoomImg($event)" src').replace(/<a\s*href/g, '<a target="_blank" href');
					data.content = $sce.trustAsHtml(data.content);
				} catch(e) {}
				$scope.questionConShow = true;
				$scope.question = data;
				$scope.quesLoadMore = false;
				$scope.question.answered = false;
				$scope.question.cogListShow = false;
				$scope.question.supply = false;
				$scope.question.supplyContent = "";
			}
		});
		$scope.getAnswers(param, false);
	}
	$scope.toggleQuestion = function(index) {
		aqid = $scope.questions[index].aqid;
		$scope.getQuestionDetial(aqid);
		$scope.aqid = aqid;
	}
	
	$scope.getQuestions = function(determineLoadMore) {
		param = {
			page: $scope.getQuestionPage,
			fields: "attention"
		}
		QuestionsService.get(param).success(function(data) {
			if(!($scope.questions)) {
				$scope.questions = [];
			}
			for(var i = 0; i < data.questionlist.length; i++) {
				data.questionlist[i].user.name = data.questionlist[i].user.name == "" ? ("萌小码_"+ data.questionlist[i].uid) : data.questionlist[i].user.name
				data.questionlist[i].content = "";
				data.questionlist[i].timeHide = true;
				data.questionlist[i].userHide = true;
				if(determineLoadMore) {
					$scope.questions.push(data.questionlist[i]);
				} else {
					$scope.questions = data.questionlist;
				}
			}
			$scope.quesLoadMore = data.loadmore;

		}).then(function(data) {
			$scope.toggleQuestion(0);
		});
	}
	$scope.getQuestions(false);
}])
angular.module('qa.navbar.directive',[])
.directive('navbarcard', ['UserService',function(UserService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/navbar.html",
		controller: function($scope){
			UserService.get().success(function(data) {
				if(data.uid != "0") {
					$scope.isLogin = true;
					if(data.name == "") {
						data.name = "萌小码_" + data.uid;
					}
					$scope.user = data;
					var mm_user_name  = $scope.user.name;
					var maxShowLen = 7;
					if(mm_user_name){
						if(mm_user_name.length>maxShowLen){
							$scope.user.name = $scope.user.name.substr(0,6)+'...';
						}
					}
				} else {
					$scope.isLogin = false;
				}
			});
			//slide navbar
			var initBlock = function(){
				if(!$(".mm_navbar_active").length) {
					$('.mm_navbar_nav').append('<div class="mm_navbar_active"></div>');
				}
				return $(".mm_navbar_active");
			};
			var isShowBlock = function(){
				var pos = 3; // 不显示滑动块
				var href = window.location.href;
				if (/^http:\/\/qa.mengma.com\/#/.test(href)) {
					pos = 2;
				} else if(/^http:\/\/oj.mengma.com\/$/.test(href)) {
					pos = 1;
				} else if(/^http:\/\/www.mengma.com\/volumes$/.test(href)) {
					pos = 0;
				}
				return pos;
			};
			var changeColor = function(index) {
		       $(".mm_navbar_nav .navbar_slide_li").each(function(index){
					$(this).find('a').removeClass("mm_navbar_nav_active");
					$(this).find('img').attr('src','http://s.mengma.com/img/mm_gray_'+index+'.svg');
		       });
		       $(".mm_navbar_nav a").eq(index).addClass("mm_navbar_nav_active");
		       $('.mm_navbar_nav_active').find('img').attr('src','http://s.mengma.com/img/mm_white_'+index+'.svg');
		    }
		    var slideBlock = function(block, width, pos, moveTime){
		    	block.stop().animate({
					left: width * pos + "",
					width: width + ""
				}, moveTime, changeColor(pos));
		    };
		    var currentPageIndex = isShowBlock();
			if(currentPageIndex < 3) { // 3个项目首页滑动效果
				var block = initBlock();
				var navbarLiWidth = $(".navbar_slide_li").eq(0).width();
				//init
				slideBlock(block, navbarLiWidth, currentPageIndex, 300);
				//slide
				$(".navbar_slide_li").find("a").mouseenter(function(e) {
					e.stopPropagation();
					slideBlock(block, navbarLiWidth, $(this).closest("a").data("type"), 300);
				});
				//mouseleave
				$(document).on("mouseleave", ".mm_navbar_nav", function(){
					slideBlock(block, navbarLiWidth, currentPageIndex, 300);
				});
			} else {//鼠标划入时候滑动 划出消失
				$(".navbar_slide_li").find("a").hover(function() {
					var navbarLiWidth = $(".navbar_slide_li").eq(0).width();
					slideBlock(initBlock(), navbarLiWidth, $(this).closest("a").data("type"), 300);
				});
				$(document).on("mouseleave", ".mm_navbar_nav", function(){
					$(".mm_navbar_active").remove();
					$(".mm_navbar_nav .navbar_slide_li").each(function(index){
						$(this).find('img').attr('src','http://s.mengma.com/img/mm_gray_'+index+'.svg');
						$(this).find('a').removeClass("mm_navbar_nav_active");
		       		});
				});
			}
			$scope.isLoginVerify = function(linkAdd) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(linkAdd != "") {
						window.location.href = "http://qa.mengma.com/#/"+linkAdd;
					}
				}
			}
			$scope.closeTip = function() {
				$("#login_tip").css("display","none");
			}
			var showImage = function(imgSrc) {
				var realWidth, realHeight, rate, imgWidth, imgHeight, marginL, marginT;
				var height = $("#maskImage").height();
				$("#maskImage").find("div").width("960px").height(height - 60).css("margin-top","30px");
				var clientWidth = $("#maskImage").find("div").width();
				var clientHeight = $("#maskImage").find("div").height();
				marginL = 0;
				marginT = 0;
				$("<img/>").attr("src", imgSrc).load(function() {
					realWidth = this.width;
					realHeight = this.height;
					widthRate = clientWidth / realWidth;
					heightRate = clientHeight / realHeight;
					if(widthRate < heightRate) {
						if(widthRate >= 1) {
							imgWidth = realWidth;
							imgHeight = realHeight;
						} else {
							imgWidth = clientWidth;
							imgHeight = realHeight*widthRate;
						}
					} else {
						if(heightRate >= 1) {
							imgWidth = realWidth;
							imgHeight = realHeight;
						} else {
							imgWidth = realWidth*heightRate;
							imgHeight = clientHeight;
						}
					}
					marginL = (clientWidth - imgWidth) / 2;
					marginT = (clientHeight - imgHeight) / 2;
					$("#maskImage").find("div").html('<img src="'+imgSrc+'" style="width:'+imgWidth+'px;height:'+imgHeight+'px">');
					$("#maskImage").find("img").css({
						"margin-left" : marginL+"px",
						"margin-top" : marginT+"px",
					});
				});
				$("#maskImage").css("display","block");
				if(navigator.userAgent.indexOf('Mac OS X') > 0) {
					$('html').css("overflow", "hidden");
				} else {
					$('html').getNiceScroll().hide();
				}
			}
			$scope.zoomImg = function(event) {
				showImage(event.target.src)
			}
			$scope.closeMask = function() {
				$("#maskImage").css("display","none");
				if(navigator.userAgent.indexOf('Mac OS X') > 0) {
					$('html').css("overflow", "auto");
				} else {
					$('html').getNiceScroll().show();
				}
			}
		}
	}
}])
angular.module('qa.directives',[])
.directive('rightcard', ['getInforService','QuestionsService','$window', '$location',function(getInforService,QuestionsService,$window,$location){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/right.html",
		controller: function($scope){
			getInforService.get("http://api.mengma.com/questions/myAttentedQNum").success(function(data) {
				$scope.myAttentedQNum = data;
			});
			getInforService.get("http://api.mengma.com/tags/getHotTagList").success(function(data) {
				$scope.hotTagList = data;
			});
			getInforService.get("http://api.mengma.com/volume/getHotVolume/33").success(function(data) {
				$scope.hotVolumes = data;
			});
			getInforService.get("http://api.mengma.com/oj/getHotOj").success(function(data) {
				$scope.hotOjList = data;
			});
			
			$scope.goAttention = function() {
				$scope.isLoginVerify("followed");
			}
			$scope.goAskQuestion = function() {
				$scope.isLoginVerify("add");
			}
			$scope.goSearch = function(event) {
				if(event.keyCode == 13) {
					$scope.searchShow = true;
					determineLoadMore = false;
					$scope.searchResults = [];
					getInforService.get("http://api.mengma.com/search/index/keyword/"+$scope.keyWord).success(function(data) {
						if(data.questions) {
							/*$scope.questionConShow = false;*/
							for(var i = 0; i < data.questions.length;i++) {
								data.questions[i].content = "";
							}
							$scope.searchResults = data.questions;
							$scope.quesLoadMore = data.loadmore;
						}
						$scope.searchNum = 0;
					});
				}
			}
			$scope.rightBoxPos = function() {
				if ($("#mm_right_box").length > 0) {
					var pl_width = $("#mm_right_box").outerWidth();
					var pl_height = $("#mm_right_box").height();
					var pl_pos = $("#mm_right_box").offset();
					var padding = $("#mm_right_box").css("padding");
					$("#mm_right_box").css({
						"position": "fixed",
						"height": pl_height + "px",
						"width": pl_width + "px",
					})
					$(window).scroll(function() {
						$("#mm_right_box").css({
							"top": Math.max(pl_pos.top + $("#mm_right_box").position().top - $("#mm_right_box").offset().top, 63)
						});
					});
				}
			}
			if($("#mm_right_box").length > 0) {
				$("#mm_right_box").css({top:"63px"});
				$scope.rightBoxPos();
			}
		}
	}
}])
.directive('questionscard', ['QuestionsService','AttentionsService','getInforService', function(QuestionsService, AttentionsService,getInforService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/question.html",
		controller: function($scope){
			$scope.popup = function(determine,title,integraled,func) {
				if(!determine) {
					data = {
						color: "#b9b9bd",
						face: ":(",
						title: title
					}
				} else {
					data = {
						color: "#36b14a",
						face: ":)",
						title: title
					}
				}
				if(integraled) {
					config = {
						width: 300,
						height: 350,
						template: document.getElementById('integral_template').innerHTML,
						data: {
							color: "#36b14a",
							title: title,
							description: "积分+5"
						}
					}
				} else {
					config = {
						width: 500,
						height: 300,
						template: document.getElementById('tip_template').innerHTML,
						data: data
					}
				}
				
				Phenix.init(config).show(function() {
					if(func != undefined) {
						func();
					} else {
						setTimeout(function() {
							Phenix.hide();
						},3000);
					}
				});
			}
			$scope.plusEnter = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				question.followed = "2";
			}
			$scope.plusLeave = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				if(question.followed == "2") {
					question.followed = "0";
				}
			}
			$scope.likeQuestion = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(index == undefined) {
						aqid = $scope.aqid;
						question = $scope.question;
					} else {
						aqid = $scope.questions[index].aqid;
						question = $scope.questions[index];
					}
					param = {
						aqid: aqid,
						fields: "like"
					}
					QuestionsService.operation('PUT',param).success(function(data) {
						if(data.code == "0") {
							question.liked = 1;
							question.like_num = parseInt(question.like_num) + 1;
						} else {
							$scope.popup(true,data.msg,false);
						}
					});
				}
			}
			$scope.cogShow = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(index == undefined) {
						question = $scope.question;
					} else {
						question = $scope.questions[index];
					}
					if(!question.cogListShow) {
						question.cogListShow = true;
					} else {
						question.cogListShow = false;
					}
				}
			}
			$scope.supplyQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				question.supply = true;
				question.cogListShow = false;
			}
			$scope.submitSupply = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				content = question.supplyContent;
				if(encodeURIComponent(content).length > 30000) {
					$scope.popup(false, "输入的内容超过长度限制", false);
					return;
				}
				if(content == "") {
					$scope.popup(false, "内容不能为空", false);
					return
				}
				param = {
					aqid: question.aqid,
					content: content
				}
				getInforService.operation('http://api.mengma.com/supplements',param,'POST').success(function(data) {
					if(data.code == "0") {
						question.supplys.push(content);
						question.supply = false;
					} else {
						$scope.popup(false, data.msg);
					}
				});
			}
			$scope.cancelSupply = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				question.supply = false;
			}
			$scope.deleteQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				param = {
					aqid: question.aqid,
					type: 2
				}
				QuestionsService.operation('DELETE', param).success(function(data) {
					question.cogListShow = false;
					if(data.code == "200001") {
						$scope.popup(true, data.msg, false);
						window.location.href="http://qa.mengma.com/#/";
					} else {
						$scope.popup(false, data.msg, false);
					}
				});
			}
			$scope.reportQuestion = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				param = {
					aqid: question.aqid,
					fields: "report"
				}
				QuestionsService.operation('PUT',param).success(function(data) {
					question.cogListShow = false;
				});
			}
		}
	};
}])
.directive('answercard', ['AnswersService','CommentService', function(AnswersService, CommentService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/answer.html",
		controller: function($scope){
			$scope.toAnswer = function(index) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(index == undefined) {
						question = $scope.question;
					} else {
						question = $scope.questions[index];
					}
					question.answered = true;
					toolbar = ['bold', 'italic', 'underline', '|', 'code', 'image', 'link', '|', 'ol', 'ul', 'blockquote', 'strikethrough','|', 'markdown'];
					editor = new Simditor({
						textarea: $("#editor-new"),
						placeholder: '请在这里输入问题描述（上传图片大小不能超过2M）',
						toolbar: toolbar,
						pasteImage: true,
						cleanPaste: true,
						upload: {
							url: 'http://api.mengma.com/questions/upload',
						},
					});
				}
			}
			$scope.submitAnswer = function(index) {
				if(index == undefined) {
					question = $scope.question;
				} else {
					question = $scope.questions[index];
				}
				content = $("#editor-new").val();
				if(content.length == 0) {
					$scope.popup(false, "内容不能为空", false);
					return;
				}
				if(encodeURIComponent(content).length > 60000) {
					$scope.popup(false, "输入的内容超过长度限制", false);
					return;
				}
				if($(".simditor-body").find("img").length > 10) {
					$scope.popup(false, "上传的图片数量不能超过10张", false);
					return;
				}
				param = {
					aqid: $scope.aqid,
					content: content
				}
				AnswersService.operation('POST', param).success(function(data) {
					if(data.code == 0) {
						$scope.popup(true, "回答成功", true);
						param = {
							aqid: $scope.aqid
						}
						$scope.getAnswers(param, false);
						$scope.getQuestionDetial();
						question.answered = false;
					} else {
						$scope.popup(false, data.msg, false);
					}
				});
			}
			$scope.likeAnswer = function(index, type) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					if(type == 0) {
						aaid = $scope.answer_s[index].aaid;
					} else {
						aaid = $scope.answer_t.aaid;
					}
					param = {
						aaid: aaid,
						answer_type: type,
						fields: "like"
					}
					AnswersService.operation('PUT', param).success(function(data) {
						if(data.code == 0) {
							if(type == 1) {
								$scope.answer_t.like_num = parseInt($scope.answer_t.like_num) + 1;
								$scope.answer_t.liked = 1;
							} else {
								$scope.answer_s[index].like_num = parseInt($scope.answer_s[index].like_num) + 1;
								$scope.answer_s[index].liked = 1;
							}
						} else {
							$scope.popup(true,data.msg,false);
						}
					});
				}
			}
			$scope.getComments = function(param, determineLoadMore){
				CommentService.get(param).success(function(data) {
					if(!($scope.comments)) {
						$scope.comments = [];
					}
					if(data.code == "400225") {
						$scope.comments = [];
					} else {
						if(data.aclist.length > 0) {
							for(var i = 0; i < data.aclist.length; i++) {
								data.aclist[i].user_infor.name = (data.aclist[i].user_infor.name == "") ? "萌小码_" + data.aclist[i].user_infor.uid : data.aclist[i].user_infor.name
								try {
									data.aclist[i].content = $sce.trustAsHtml(data.aclist[i].content);
								}catch(e){}
								if(determineLoadMore) {
									$scope.comments.push(data.aclist[i]);
								} else {
									$scope.comments = data.aclist;
								}
							}
						}
					}
					$scope.commentLoadMoreShow = data.loadmore;
				});
			}
			$scope.toggleComment = function(index, answerType) {
				if(!$scope.isLogin) {
					$("#login_tip").css("display","block");
				} else {
					$scope.commentUser = "";
					$scope.answerType = answerType;
					if(answerType == 0) {
						if(!$scope.answer_s[index].commented) {
							$scope.answer_s[index].commented = true;
							param = {
								aaid: $scope.answer_s[index].aaid,
								answer_type: answerType
							}
							$scope.getComments(param, false);
						} else {
							$scope.answer_s[index].commented = false;
						}
					} else {
						if(!$scope.answer_t.commented) {
							$scope.answer_t.commented = true;
							param = {
								aaid: $scope.answer_t.aaid,
								answer_type: answerType
							}
							$scope.getComments(param, false);
						} else {
							$scope.answer_t.commented = false;
						}
					}
				}
			}
			$scope.answerLoadMore = function(index) {
				$scope.answerPage++;
				param = {
					aqid: $scope.aqid,
					page: $scope.answerPage
				}
				$scope.getAnswers(param, true);
			}
		}
	};
}])
.directive('commentcard', ['CommentService', function(CommentService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/comment.html",
		controller: function($scope){
			$scope.commentPage = 0;
			$scope.submitComentContent = "";
			$scope.commentLoadMore = function(index) {
				$scope.commentPage++;
				if($scope.answerType == 0) {
					aaid: $scope.answer_s[index].aaid;
				} else {
					aaid: $scope.answer_t.aaid;
				}
				param = {
					aaid: aaid,
					answer_type: $scope.answerType,
					page: $scope.commentPage
				}
				$scope.getComments(param, true);
			}
			$scope.submitComment = function(index) {
				content = $scope.submitComentContent;
				if(content == "") {
					$scope.popup(false, "内容不能为空", false);
					return;
				}
				if(encodeURIComponent(content).length > 10000) {
					$scope.popup(false, "输入的内容超过长度限制", false);
					return;
				}
				if($scope.answerType == 0) {
					answer = $scope.answer_s[index];
				} else {
					answer = $scope.answer_t;
				}
				param = {
					aaid: answer.aaid,
					content: content,
					answer_type: $scope.answerType
				}
				CommentService.operation('POST', param).success(function(data) {
					if(data.code == 0) {
						Param = {
							aaid: answer.aaid,
							answer_type: $scope.answerType
						}
						$scope.getComments(Param, false);
						$scope.submitComentContent = "";
						answer.comment_num = parseInt(answer.comment_num) + 1;
					} else {
						$scope.popup(false, data.msg);
					}
				});

			}
		}
	};
}])
.directive('followrightcard', ['QuestionsService', function(QuestionsService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/followRight.html",
		controller: function($scope){
			$scope.scroll = function() {
				if(!(navigator.userAgent.indexOf('Mac OS X') > 0)) {
					$('#left-fix').niceScroll({
						styler:"fb", 
						cursorwidth:"8px",
						cursorcolor:"#7a7777",
						cursorborder:"",
						horizrailenabled: false,
						zindex:99
					});
					$('.middle-right-scroll').niceScroll({
						styler:"fb", 
						cursorwidth:"8px",
						cursorcolor:"#7a7777",
						cursorborder:"",
						horizrailenabled: false,
						zindex:99
					});
				}
			}
			$scope.scroll();
		}
	}
}])
.directive('searchcard', ['QuestionsService', function(QuestionsService){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: "templates/directives/search.html",
		controller: function($scope){

		}
	}
}])

